package com.zdp.seckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zdp.seckill.common.enums.EmBusinessError;
import com.zdp.seckill.common.exception.BusinessException;
import com.zdp.seckill.common.utils.AssertUtil;
import com.zdp.seckill.common.validator.ValidationResult;
import com.zdp.seckill.common.validator.ValidatorImpl;
import com.zdp.seckill.mapper.UserInfoMapper;
import com.zdp.seckill.mapper.UserPasswordMapper;
import com.zdp.seckill.pojo.UserInfo;
import com.zdp.seckill.pojo.UserPassword;
import com.zdp.seckill.pojo.vo.UserModel;
import com.zdp.seckill.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * @author sesshomaru
 * @date 2021/6/17
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private UserPasswordMapper userPasswordMapper;

    @Autowired
    private ValidatorImpl validator;

    @Override
    public UserModel validateLogin(String telphone, String encrptPassword) {
        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
        userInfoQueryWrapper.eq("telphone", telphone);
        UserInfo userInfo = userInfoMapper.selectOne(userInfoQueryWrapper);
        AssertUtil.isNotNull(userInfo, "用户主题为空");
        QueryWrapper<UserPassword> userPasswordQueryWrapper = new QueryWrapper<>();
        userPasswordQueryWrapper.eq("user_id", userInfo.getId());
        UserPassword userPassword = userPasswordMapper.selectOne(userPasswordQueryWrapper);
        AssertUtil.isNotNull(userPassword, "用户密码数据为空");
        String userPasswordEncrptPassword = userPassword.getEncrptPassword();
        AssertUtil.strEquals(encrptPassword, userPasswordEncrptPassword, "密码不一致");

        return convertFormDataObject(userInfo, userPassword);
    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    @Override
    public void register(UserModel userModel) {
        /*
        通过Validation验证参数
        ValidationResult validationResult = validator.validate(userModel);
        if (validationResult.isHasErrors()) {
            throw new BusinessException(validationResult.getErrMsg());
        }*/
        AssertUtil.isNotNull(userModel, EmBusinessError.PARAMETER_VALIDATION_ERROR);
        String encrptPassword = userModel.getEncrptPassword();
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(userModel, userInfo);
        boolean flag = false;
        try {
            flag = userInfoMapper.insert(userInfo) > 0;
            // 捕获唯一索引重复添加时的异常
        }catch (DuplicateKeyException e) {
            throw new BusinessException("手机号已存在!~");
        }
        // 如果主题添加数小于0
        AssertUtil.isTrue(!flag, "用户主体信息添加异常");
        Integer userId = userInfo.getId();
        UserPassword userPassword = new UserPassword();
        userPassword.setUserId(userId);
        userPassword.setEncrptPassword(encrptPassword);
        userPasswordMapper.insert(userPassword);
    }

    @Override
    public UserModel getUserById(Integer id) {
        UserInfo userInfo = userInfoMapper.selectById(id);
        AssertUtil.isNotNull(userInfo, "userInfo对象不存在");
        QueryWrapper<UserPassword> userPasswordQueryWrapper = new QueryWrapper<>();
        userPasswordQueryWrapper.eq("user_id", id);
        UserPassword userPassword = userPasswordMapper.selectOne(userPasswordQueryWrapper);
        return convertFormDataObject(userInfo, userPassword);
    }

    private UserModel convertFormDataObject(UserInfo userInfo, UserPassword userPassword) {
        AssertUtil.isNotNull(userInfo, "userInfo对象为空");
        UserModel userModel = new UserModel();
        BeanUtils.copyProperties(userInfo, userModel);

        if (Optional.ofNullable(userPassword).isPresent()) {
            userModel.setEncrptPassword(userPassword.getEncrptPassword());
        }
        return userModel;
    }

}
